import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Button, Typography, Row, Col, Image, Tag, Space, Progress, message, Avatar, Modal } from 'antd';
import { PlayCircleOutlined, HeartOutlined, ShareAltOutlined, UserOutlined, ClockCircleOutlined, ShoppingCartOutlined, CloseOutlined, ArrowLeftOutlined, FileTextOutlined, FilePdfOutlined, FileWordOutlined, FilePptOutlined, FileExcelOutlined } from '@ant-design/icons';
import axios from 'axios';

const { Title, Text, Paragraph } = Typography;

export default function CourseDetail() {
  const { courseId } = useParams();
  const navigate = useNavigate();
  const [course, setCourse] = useState(null);
  const [loading, setLoading] = useState(true);
  const [trialActive, setTrialActive] = useState(false);
  const [trialTimeLeft, setTrialTimeLeft] = useState(60);
  const [videoModalVisible, setVideoModalVisible] = useState(false);
  const [currentVideo, setCurrentVideo] = useState(null);
  const videoRef = useRef(null);
  const timerRef = useRef(null);

  // 返回课程列表页
  const handleBackToList = () => {
    navigate('/coursess');
  };

  // 获取课程详情
  const fetchCourseDetail = async () => {
    try {
      const response = await axios.get(`http://localhost:3001/api/courses/${courseId}`);
      if (response.data.success) {
        setCourse(response.data.data);
      } else {
        message.error('获取课程详情失败');
      }
    } catch (error) {
      console.error('获取课程详情错误:', error);
      message.error('获取课程详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 开始试看
  const handleTrialWatch = () => {
    if (!course?.videoResources || course.videoResources.length === 0) {
      message.warning('该课程暂无视频内容');
      return;
    }

    // 获取第一个视频
    const firstVideo = course.videoResources[0];
    setCurrentVideo(firstVideo);
    setVideoModalVisible(true);
    setTrialActive(true);
    setTrialTimeLeft(60);
    
    // 清除之前的定时器
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }
    
    timerRef.current = setInterval(() => {
      setTrialTimeLeft((prev) => {
        if (prev <= 1) {
          clearInterval(timerRef.current);
          setTrialActive(false);
          setVideoModalVisible(false);
          message.warning('试看时间结束，请购买课程继续观看');
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  // 关闭视频播放器
  const handleCloseVideo = () => {
    setVideoModalVisible(false);
    setTrialActive(false);
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }
    if (videoRef.current) {
      videoRef.current.pause();
    }
  };

  // 购买课程
  const handlePurchase = () => {
    message.success('购买功能开发中');
  };

  // 收藏课程
  const handleCollect = () => {
    message.success('课程已收藏');
  };

  // 分享课程
  const handleShare = () => {
    message.success('分享功能开发中');
  };

  // 获取文件类型和图标
  const getFileTypeIcon = (fileName) => {
    const lowerFileName = fileName.toLowerCase();
    if (lowerFileName.endsWith('.pdf')) {
      return <FilePdfOutlined style={{ color: '#f5222d' }} />;
    } else if (lowerFileName.endsWith('.doc') || lowerFileName.endsWith('.docx')) {
      return <FileWordOutlined style={{ color: '#1890ff' }} />;
    } else if (lowerFileName.endsWith('.ppt') || lowerFileName.endsWith('.pptx')) {
      return <FilePptOutlined style={{ color: '#fa8c16' }} />;
    } else if (lowerFileName.endsWith('.xls') || lowerFileName.endsWith('.xlsx')) {
      return <FileExcelOutlined style={{ color: '#52c41a' }} />;
    } else {
      return <FileTextOutlined style={{ color: '#666' }} />;
    }
  };

  // 处理文档下载
  const handleDocumentDownload = (fileUrl, fileName) => {
    const link = document.createElement('a');
    link.href = fileUrl.startsWith('http') ? fileUrl : `http://localhost:3001${fileUrl}`;
    link.download = fileName;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  useEffect(() => {
    fetchCourseDetail();
  }, [courseId]);

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '50vh',
        fontSize: '16px',
        color: '#666'
      }}>
        加载中...
      </div>
    );
  }

  if (!course) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '50vh',
        fontSize: '16px',
        color: '#666'
      }}>
        课程不存在
      </div>
    );
  }

  return (
    <div style={{ 
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)',
      padding: '16px',
      paddingTop: '80px',
      overflowX: 'hidden'
    }}>
      <div style={{ maxWidth: '1200px', margin: '0 auto' }}>
        {/* 返回按钮 */}
        <div style={{ 
          marginBottom: '16px',
          display: 'flex',
          alignItems: 'center'
        }}>
          <Button 
            type="text" 
            icon={<ArrowLeftOutlined />} 
            onClick={handleBackToList}
            style={{ 
              fontSize: '16px',
              color: '#1890ff',
              padding: '8px 12px',
              borderRadius: '6px',
              border: '1px solid #d9d9d9',
              background: '#fff'
            }}
          >
            返回课程
          </Button>
        </div>

        {/* 课程头部信息 */}
        <Card 
          style={{ 
            marginBottom: '24px',
            borderRadius: '12px',
            boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)',
            border: 'none',
            overflow: 'hidden'
          }}
        >
          <Row gutter={[16, 16]}>
            <Col xs={24} sm={24} md={8}>
              {course.coverImageUrls && course.coverImageUrls.length > 0 ? (
                <Image
                  width="100%"
                  style={{ borderRadius: '8px' }}
                  src={course.coverImageUrls[0].startsWith('http') ? course.coverImageUrls[0] : `http://localhost:3001${course.coverImageUrls[0]}`}
                  fallback=""
                />
              ) : (
                <Image
                  width="100%"
                  style={{ borderRadius: '8px' }}
                  src=""
                />
              )}
            </Col>
            <Col xs={24} sm={24} md={16}>
              <div style={{ padding: '0 8px' }}>
                <Title level={2} style={{ 
                  marginBottom: '16px', 
                  color: '#333',
                  fontSize: window.innerWidth < 768 ? '20px' : '24px',
                  wordBreak: 'break-word'
                }}>
                  {course.name}
                </Title>
                
                <div style={{ marginBottom: '16px' }}>
                  <Space wrap>
                    <Avatar src={course.teacher?.avatar} icon={<UserOutlined />} />
                    <Text strong style={{ fontSize: '16px' }}>{course.teacherName}</Text>
                    <Tag color="blue" style={{ fontSize: '12px' }}>讲师</Tag>
                  </Space>
                </div>
                
                <div style={{ marginBottom: '24px' }}>
                  <Row gutter={[8, 8]}>
                    <Col xs={24} sm={8}>
                      <Text style={{ fontSize: '14px' }}>
                        <PlayCircleOutlined style={{ marginRight: '4px' }} /> 
                        视频数量: {course.videoResources?.length || 0}
                      </Text>
                    </Col>
                    <Col xs={24} sm={8}>
                      <Text style={{ fontSize: '14px' }}>
                        <ClockCircleOutlined style={{ marginRight: '4px' }} /> 
                        课程时长: 12小时
                      </Text>
                    </Col>
                    <Col xs={24} sm={8}>
                      <Text style={{ fontSize: '14px' }}>
                        <UserOutlined style={{ marginRight: '4px' }} /> 
                        学习人数: 1,234
                      </Text>
                    </Col>
                  </Row>
                </div>

                <div style={{ marginBottom: '24px' }}>
                  <Space size="large" wrap>
                    <Text style={{ fontSize: '24px', color: '#f5222d', fontWeight: 'bold' }}>
                      ¥{(course.price / 100).toFixed(2)}
                    </Text>
                    <Text delete style={{ fontSize: '16px', color: '#999' }}>¥299.00</Text>
                    <Tag color="red" style={{ fontSize: '12px' }}>限时优惠</Tag>
                  </Space>
                </div>

                <div>
                  <Space size="middle" wrap style={{ width: '100%' }}>
                    <Button 
                      type="primary" 
                      size="large" 
                      icon={<PlayCircleOutlined />}
                      onClick={handleTrialWatch}
                      disabled={trialActive}
                      style={{ borderRadius: '6px' }}
                    >
                      免费试看
                    </Button>
                    <Button 
                      type="primary" 
                      size="large" 
                      icon={<ShoppingCartOutlined />}
                      onClick={handlePurchase}
                      style={{ borderRadius: '6px' }}
                    >
                      立即购买
                    </Button>
                    <Button 
                      icon={<HeartOutlined />}
                      onClick={handleCollect}
                      style={{ borderRadius: '6px' }}
                    >
                      收藏
                    </Button>
                    <Button 
                      icon={<ShareAltOutlined />}
                      onClick={handleShare}
                      style={{ borderRadius: '6px' }}
                    >
                      分享
                    </Button>
                  </Space>
                </div>
              </div>
            </Col>
          </Row>
        </Card>

        {/* 试看倒计时 */}
        {trialActive && (
          <Card 
            style={{ 
              marginBottom: '24px',
              borderRadius: '12px',
              boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)',
              border: 'none'
            }}
          >
            <div>
              <Text strong style={{ fontSize: '16px', color: '#1890ff' }}>
                试看倒计时：{trialTimeLeft}秒
              </Text>
              <Progress 
                percent={((60 - trialTimeLeft) / 60) * 100} 
                status="active"
                strokeColor="#1890ff"
                style={{ marginTop: '8px' }}
              />
            </div>
          </Card>
        )}

        {/* 课程内容 */}
        <Card 
          style={{ 
            borderRadius: '12px',
            boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)',
            border: 'none',
            overflow: 'hidden'
          }}
        >
          <Title level={4} style={{ marginBottom: '16px', color: '#333' }}>课程简介</Title>
          <Paragraph style={{ 
            fontSize: '14px', 
            lineHeight: '1.6', 
            color: '#666',
            wordBreak: 'break-word'
          }}>
            {course.description}
          </Paragraph>
          
          <Title level={4} style={{ marginBottom: '16px', marginTop: '24px', color: '#333' }}>课程大纲</Title>
          <div>
            {course.videoResources && course.videoResources.length > 0 ? (
              course.videoResources.map((video, index) => (
                <div 
                  key={index} 
                  style={{ 
                    padding: '12px 0', 
                    borderBottom: '1px solid #f0f0f0',
                    display: 'flex',
                    alignItems: 'center',
                    flexWrap: 'wrap'
                  }}
                >
                  <Space style={{ width: '100%' }} wrap>
                    <PlayCircleOutlined style={{ color: '#1890ff', fontSize: '16px' }} />
                    <Text style={{ 
                      flex: 1, 
                      fontSize: '14px',
                      wordBreak: 'break-word',
                      minWidth: '200px'
                    }}>
                      第{index + 1}节：{video.name}
                    </Text>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      时长：{video.duration || '未知'}
                    </Text>
                    <Tag color={trialActive ? 'green' : 'default'} style={{ fontSize: '12px' }}>
                      {trialActive ? '试看中' : '未购买'}
                    </Tag>
                  </Space>
                </div>
              ))
            ) : (
              <Text type="secondary" style={{ fontSize: '14px' }}>暂无课程内容</Text>
            )}
          </div>

          {/* 课程文档 */}
          {course.fileUrls && course.fileUrls.length > 0 && (
            <>
              <Title level={4} style={{ marginBottom: '16px', marginTop: '24px', color: '#333' }}>课程文档</Title>
              <div>
                {course.fileUrls.map((fileUrl, index) => {
                  // 从URL中提取文件名
                  const fileName = fileUrl.split('/').pop() || `文档${index + 1}`;
                  return (
                    <div 
                      key={index} 
                      style={{ 
                        padding: '12px 0', 
                        borderBottom: '1px solid #f0f0f0',
                        display: 'flex',
                        alignItems: 'center',
                        flexWrap: 'wrap'
                      }}
                    >
                      <Space style={{ width: '100%' }} wrap>
                        {getFileTypeIcon(fileName)}
                        <Text style={{ 
                          flex: 1, 
                          fontSize: '14px',
                          wordBreak: 'break-word',
                          minWidth: '200px'
                        }}>
                          {fileName}
                        </Text>
                        <Button 
                          type="link" 
                          size="small"
                          onClick={() => handleDocumentDownload(fileUrl, fileName)}
                          style={{ padding: '4px 8px' }}
                        >
                          下载
                        </Button>
                        <Tag color="blue" style={{ fontSize: '12px' }}>
                          文档
                        </Tag>
                      </Space>
                    </div>
                  );
                })}
              </div>
            </>
          )}
        </Card>
      </div>

      {/* 视频播放模态框 */}
      <Modal
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ 
              fontSize: window.innerWidth < 768 ? '14px' : '16px',
              wordBreak: 'break-word'
            }}>
              试看视频 - {currentVideo?.name}
            </span>
            <Button 
              type="text" 
              icon={<CloseOutlined />} 
              onClick={handleCloseVideo}
              style={{ marginRight: '-12px' }}
            />
          </div>
        }
        open={videoModalVisible}
        onCancel={handleCloseVideo}
        footer={null}
        width={window.innerWidth < 768 ? '95%' : 800}
        centered
        destroyOnClose
        style={{ top: window.innerWidth < 768 ? '10px' : undefined }}
      >
        <div style={{ textAlign: 'center' }}>
          {currentVideo && (
            <video
              ref={videoRef}
              controls
              style={{ 
                width: '100%', 
                maxHeight: window.innerWidth < 768 ? '300px' : '450px',
                borderRadius: '8px'
              }}
              src={currentVideo.videoUrl.startsWith('http') 
                ? currentVideo.videoUrl 
                : `http://localhost:3001${currentVideo.videoUrl}`
              }
              onError={(e) => {
                console.error('视频加载失败:', e);
                message.error('视频加载失败，请检查视频文件');
              }}
            >
              您的浏览器不支持视频播放
            </video>
          )}
          <div style={{ marginTop: '16px' }}>
            <Text type="secondary">
              试看时间剩余：{trialTimeLeft}秒
            </Text>
          </div>
        </div>
      </Modal>
    </div>
  );
} 